import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'

// create an axios instance
const instance = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

// request interceptor
instance.interceptors.request.use(

  // let token = getToken()
  //   if (token) {
  //     config.headers['Authorization'] = `Bearer ${token}`
  //   } else {
  //     let temp = process.env.VUE_APP_SERVER_AUTHORIZATION
  //     if (temp) {
  //       config.headers['Authorization'] = `Bearer ${temp}`
  //     }
  //   }

  config => {
    let token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    } else {
      let temp = process.env.VUE_APP_SERVER_AUTHORIZATION
      if (temp) {
        config.headers['Authorization'] = `Bearer ${temp}`
      }
    }
    // Do something before request is sent
    // if (store.getters.token) {
    // config.headers['Authorization'] =
    //   `ew0KICAgICJhdWQiOiBbDQogICAgICAgICJ4dWVjaGVuZy1yZXNvdXJjZSINCiAgICBdLA0KICAgICJwYXlsb2FkIjogew0KICAgICAgICAiMTE3NzE0NDIwOTQ2MzEyODEyNSI6IHsNCiAgICAgICAgICAgICJyZXNvdXJjZXMiOiBbDQogICAgICAgICAgICBdLA0KICAgICAgICAgICAgInVzZXJfYXV0aG9yaXRpZXMiOiB7DQogICAgICAgICAgICAgICAgInJfMDAxIjogWw0KICAgICAgICAgICAgICAgICAgICAieGNfY29tcGFueV9tb2RpZnkiLA0KCQkJCQkieGNfY29tcGFueV92aWV3IiwNCgkJCQkJInhjX2NvdXJzZV9iYXNlX2RlbCIsDQoJCQkJCSJ4Y19jb3Vyc2VfYmFzZV9lZGl0IiwNCgkJCQkJInhjX2NvdXJzZV9iYXNlX2xpc3QiLA0KCQkJCQkieGNfY291cnNlX2Jhc2Vfc2F2ZSIsDQoJCQkJCSJ4Y19jb3Vyc2VfYmFzZV92aWV3IiwNCgkJCQkJInhjX2NvdXJzZV9wdWJsaXNoIiwNCgkJCQkJInhjX21hcmtldF9zYXZlX21vZGlmeSIsDQoJCQkJC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2xpZW50X2F1dGhvcml0aWVzIjogWw0KICAgICAgICAiUk9MRV9VU0VSIg0KICAgIF0sDQogICAgImp0aSI6ICIxZWI3ZTk4Ny1kN2MyLTQwZjUtYjBkNi1jZDYxMzljYjE4ZTAiLA0KICAgICJjbGllbnRfaWQiOiAieGMtY29tLXBsYXRmb3JtIg0KfQ==`
    // config.headers['Authorization'] = process.env.VUE_APP_SERVER_AUTHORIZATION
    // config.headers['Authorization'] = `Bearer ${getToken()}` // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // }

    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)
// respone interceptor
instance.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const code = response.status
    if (code !== 200) {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      // 401
      if (code === 401) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject(new Error('error'))
    } else {
      return response
    }
  },
  error => {
    Message({
      message: error.response.data.errMessage,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export const createAPI = (url, method, data) => {
  let config = {}
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  return instance({
    url,
    method,
    ...config
  })
}

export const createFormAPI = (url, method, data) => {
  let config = {}
  config.data = data
  config.headers = {
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  config.responseType = 'json'
  config.transformRequest = [
    function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }
  ]
  return instance({
    url,
    method,
    ...config
  })
}
